﻿/* Derived from CART.DLL, Cart Plugin for KSP.
Original Author: Tony Chernogovsky, SPb, Russia.
Previous Maintainer: Callum King-Underwood, England.
Current Maintainer: Andrea Cappelletti, Milan, Italy aka CleverWalrus.
License: CC-BY-SA, Attribution & Share-alike Creative Common Licence. 
Feel free to modify as long as:
a) original author is mentioned, and 
b) you distribute your code under the same license.*/

using UnityEngine;
namespace CleverBobCat.WheeledVehicle
{
    public class SmoothControl
    {
        private float mValuePerSecond = 5F;
        private float mCurrentValue = 0;
        private float mTargetValue = 0;
        private float mStartTime = 0;
        private float mStartValue = 0;
        private float mIncrement = 0;
        private bool mTargetReached = false;

        public SmoothControl(float valuePerSecond)
        {
            mValuePerSecond = valuePerSecond;
        }

        public float value
        {
            get
            {
                if (!mTargetReached)
                {
                    mCurrentValue = mStartValue +
                                    (Time.time - mStartTime) * mIncrement;
                    if ((mIncrement > 0 && mCurrentValue > mTargetValue) ||
                        (mIncrement < 0 && mCurrentValue < mTargetValue))
                    {
                        mTargetReached = true;
                        mCurrentValue = mTargetValue;
                    }
                }
                return mCurrentValue;
            }

            set
            {
                if (mTargetValue != value)
                {
                    mTargetValue = value;
                    mTargetReached = false;
                    mStartTime = Time.time;
                    mStartValue = mCurrentValue;
                    mIncrement = mValuePerSecond *
                                 Mathf.Sign(mTargetValue - mCurrentValue);
                }
            }
        }

        public float currentValue
        {
            get { return mTargetValue; }
            set
            {
                mTargetValue = value;
                mCurrentValue = value;
                mTargetReached = true;
            }
        }

        public static implicit operator float(SmoothControl v)
        {
            return v.value;
        }
    }
}